package leetcode;

/**
 * @author ：徐梦轲
 * @date ：2022/5/22 0022 17:05
 */

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

public class Solution {
    //解法1：迭代法
    //时间复杂度：O(n) 空间复杂度：O(1)
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        while(head != null) {
            ListNode temp = head.next;
            head.next = pre;
            pre = head;
            head = temp;
        }
        return pre;
    }

    //解法2：递归法
    //时间复杂度：O(n) 空间复杂度：O(n)
    public ListNode reverseList2(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

    //解法3：巧妙解法 （了解一下）
    //时间复杂度：O(n) 空间复杂度：O(n)
    public ListNode reverseList3(ListNode head) {
        ListNode ans = null;
        for (ListNode x = head; x != null; x = x.next) {
            ans = new ListNode(x.val,ans);
        }
        return ans;
    }
}
